package org.smr.ministore.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.blade.msg.Message;
import org.blade.utils.Pager;
import org.smr.ministore.entities.Authority;
import org.smr.ministore.entities.User;
import org.smr.ministore.micro.client.FeignUserMicroServiceClient;
import org.smr.ministore.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller("UserController")
public class UserController {

/*
	@Resource
	private UserService service;
*/


	@Resource
	private FeignUserMicroServiceClient service;
	/**
	 * 保存编辑后的User信息
	 * @param User
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.PATCH, value = "/User/edit")
	public Message modify(@RequestBody User User){
		Message msg = new Message();
		
		if(null == User.getId()){
			msg.setStatus(service.save(User));
		}else{
			msg.setStatus(service.updateById(User));
		}
		return msg;
	}
	
	/**
	* 跳转到列表查询User
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/User/list-page")
	public String toList(){
		return "/User/User-list";
	}

	/**
	*  根据id查询User
	* @return
	*/
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/User/{id}")
	public User get( @PathVariable Long id ){
		return service.queryById(id);
	}


    /**
	 * 分页查询User信息
	 * @param User
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/User/list/{pageSize}/{pageNum}")
	public Pager<User> list(@RequestBody User User , @PathVariable("pageSize") long pageSize, @PathVariable("pageNum")long pageNum ){

		return service.paginate(User, pageSize, pageNum);
	}
	
	
	/**
	 * 根据ID删除User信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/User/remove",method = RequestMethod.DELETE)
	public Message remove( Long id){
		
		Message msg = new Message();
		msg.setStatus(service.deleteById(id));
		return msg;
	}

	/**
	 * 根据用户名查询
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/User/getByUserName",method = RequestMethod.GET)
	public User getByUserName(HttpServletRequest request, HttpServletResponse response,  String userName ){

		User user = service.queryByUserName( userName );
		List<Authority> authorities = service.getAuthoritiesByUser(user.getId());
		request.getSession().setAttribute("authorities",authorities);
		return user;
	}


}
